package com.yeqiangwei.commons.util;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * @author HongGuang
 */
public class PaginationHelper {
	
	private static final String _URI_PREFIX = "_URI_PREFIX";
	private static final String _URI_SUFFIX = "_URI_SUFFIX";
	private static final String _PAGINATION = "pagination";
	private static final String _PAGINATION_OBJ = "Pagination";
	
	public static String arg(String url){
		if(url.endsWith("?")){
			return "";
		}else{
			return "&";
		}
	}
	
	public static void setURIAttribute(HttpServletRequest request
			, String prefix, String suffix) {
		request.setAttribute(_URI_PREFIX, prefix);
		request.setAttribute(_URI_SUFFIX, suffix);
	}
	
	public static void setAttribute(HttpServletRequest request
			, Pagination pagination) {
		if(pagination == null){
			return ;
		}
		StringBuilder uri_begin = new StringBuilder();
		if(!ValidatorHelper.isEmpty(request.getAttribute(_URI_PREFIX))) {
			String prefix = String.valueOf(request.getAttribute(_URI_PREFIX));
			String suffix = String.valueOf(request.getAttribute(_URI_SUFFIX));
			request.setAttribute(_PAGINATION, pagination.toString(prefix, suffix));
			request.setAttribute(_PAGINATION_OBJ, pagination);
			return ;
		}
		//
		String URI = request.getRequestURI().replace("//", "/");
		uri_begin.append(URI);
		uri_begin.append("?");
		if(!ValidatorHelper.isEmpty(pagination.getElements())){
			Iterator<String> it = pagination.getElements().keySet().iterator();
        	while(it.hasNext()){
    			String key = it.next();
    			if(pagination.getElements().get(key) == null) {
    				continue;
    			}
    			String tmp = pagination.getElements().get(key).toString();
    			uri_begin.append(arg(uri_begin.toString()));
    			uri_begin.append(key);
    			uri_begin.append("=");
				uri_begin.append(encode(tmp, "utf-8", StringHelper.EMPTY));
    			request.setAttribute(key, pagination.getElements().get(key));
        	}
		}
		uri_begin.append(arg(uri_begin.toString()));
		uri_begin.append("page=");
		request.setAttribute(_PAGINATION, pagination.toString(uri_begin.toString(), StringHelper.EMPTY));
		request.setAttribute(_PAGINATION_OBJ, pagination);
	}
	
    private static final String encode(String str, String enc, String def){
    	if(!ValidatorHelper.isEmpty(str)){
        	try {
                return java.net.URLEncoder.encode(str, enc);
            } catch (UnsupportedEncodingException e) {
                return def;
            }
        } else {
        	return def;
        }
    }
}
